package com.wephone.Student.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.wephone.Student.R;
import com.wephone.Student.bean.ZhidaoSearchResponse;
import com.wephone.Student.bean.data.ZhidaoAskData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.PullToRefreshView;
import com.wephone.Student.util.PullToRefreshView.OnFooterRefreshListener;
import com.wephone.Student.util.PullToRefreshView.OnHeaderRefreshListener;

public class ZhidaoSearchActivity extends BaseActivity {
	private EditText searchNameEdit;
	private TextView addQuestionText;
	private PullToRefreshView pullToRefreshListView;
	private ListView listView;
	private ListViewAdapter adapter;
	private int keyLength=0;
	private List<ZhidaoAskData> results = new ArrayList<ZhidaoAskData>();
	private TextView guojiaText1,guojiaText2,guojiaText3,guojiaText4;
	private TextView biaoqianText1,biaoqianText2,biaoqianText3,biaoqianText4,biaoqianText5;
	private String country;
	private String tag;
	private View shaixuanLayout;
	private TextView addShaixuanText;
	private ImageView addShaixuanImage;
	private boolean isChooseCountry = false;
	
//	private MyResponseHandler getHandler(){
//		MyResponseHandler handler = new MyResponseHandler(ZhidaoSearchActivity.this,ZhidaoSearchResponse.class){
//			@Override
//			public void onSuccess(String result) {
//				super.onSuccess(result);
//				
//				if(getDataSuccess){
//					ZhidaoSearchResponse res = (ZhidaoSearchResponse)response;
//					
//					if(res.getData().getList()==null || adapter.pageIdx>=res.getData().getList().size() || res.getData().getList().size()<Constants.PAGE_SIZE){
//						adapter.hasMore = false;
//					}else{
//						adapter.pageIdx++;
//					}
//					if(res.getData().getList()!=null){
//						results.addAll(res.getData().getList());
//						adapter.notifyDataSetChanged();
//					}
//				}
//			}
//		};
//		return handler;
//	}
	
	private AsyncHttpResponseHandler getHandler(){
		AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String result) {
				View pullRefreshView = findViewById(R.id.pull_refresh_listview);
				if(pullRefreshView!=null){
					((PullToRefreshView)pullRefreshView).onHeaderRefreshComplete();
					((PullToRefreshView)pullRefreshView).onFooterRefreshComplete();
				}
				if(!TextUtils.isEmpty(result)){
					try{
						Gson gson = new Gson();
						ZhidaoSearchResponse res = (ZhidaoSearchResponse)gson.fromJson(result, ZhidaoSearchResponse.class);
//						System.out.println("---message---"+res.getErrorMsg());
						if(res.getErrNo()!=null && !res.getErrNo().equals("0")){
							if(isChooseCountry){
								isChooseCountry = false;
								new AlertDialog.Builder(ZhidaoSearchActivity.this)
								.setTitle("提示")
								.setMessage("找不到相同问题，是否添加新问题？")
								.setNegativeButton("取消", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
									}
								})
								.setPositiveButton("添加", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int whichButton) {
										Bundle bundle = new Bundle();
										bundle.putString("searchName", searchNameEdit.getText().toString());
										startActivity(new Intent(getApplicationContext(),ZhidaoAddQuestionActivity.class).putExtras(bundle));
										searchNameEdit.getText().clear();
									}
								}).show();
							}
							findViewById(R.id.zhidao_no_data_text).setVisibility(View.VISIBLE);
						}else{
							if(res.getData().getList()==null || adapter.pageIdx>=res.getData().getList().size() || res.getData().getList().size()<Constants.PAGE_SIZE){
								adapter.hasMore = false;
							}else{
								adapter.pageIdx++;
							}
							if(res.getData().getList()!=null){
								results.addAll(res.getData().getList());
								adapter.notifyDataSetChanged();
							}
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
			
		};
		return handler;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zhidao_search);
		
		init();
	}
	
	private void init(){
		guojiaText1 = (TextView)findViewById(R.id.top_guojia_tv_1);
		guojiaText2 = (TextView)findViewById(R.id.top_guojia_tv_2);
		guojiaText3 = (TextView)findViewById(R.id.top_guojia_tv_3);
		guojiaText4 = (TextView)findViewById(R.id.top_guojia_tv_other);
		biaoqianText1 = (TextView)findViewById(R.id.top_biaoqian_tv_1);
		biaoqianText2 = (TextView)findViewById(R.id.top_biaoqian_tv_2);
		biaoqianText3 = (TextView)findViewById(R.id.top_biaoqian_tv_3);
		biaoqianText4 = (TextView)findViewById(R.id.top_biaoqian_tv_4);
		biaoqianText5 = (TextView)findViewById(R.id.top_biaoqian_tv_5);
		shaixuanLayout = findViewById(R.id.question_shaixuan_layout);
		addShaixuanText = (TextView)findViewById(R.id.add_shaixuan_text);
		addShaixuanImage = (ImageView)findViewById(R.id.add_shaixuan_image);
		
		findViewById(R.id.zhidao_no_data_text).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(ZhidaoSearchActivity.this)
				.setTitle("提示")
				.setMessage("找不到相同问题，是否添加新问题？")
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				})
				.setPositiveButton("添加", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Bundle bundle = new Bundle();
						bundle.putString("searchName", searchNameEdit.getText().toString());
						startActivity(new Intent(getApplicationContext(),ZhidaoAddQuestionActivity.class).putExtras(bundle));
						searchNameEdit.getText().clear();
					}
				}).show();
			}
		});
		
		addShaixuanImage.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(shaixuanLayout.getVisibility()==View.GONE){
					shaixuanLayout.setVisibility(View.VISIBLE);
					addShaixuanText.setText("关闭筛选");
					addShaixuanImage.setImageResource(R.drawable.choose_switch_on);
				}else{
					shaixuanLayout.setVisibility(View.GONE);
					addShaixuanText.setText("添加筛选");
					addShaixuanImage.setImageResource(R.drawable.choose_switch_off);
				}
			}
		});
		
		guojiaText1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(!TextUtils.isEmpty(country) && country.equals("美国")){
					country = "";
					guojiaText1.setBackgroundResource(R.drawable.label_textfour_default);
				}else{
					country = "美国";
					guojiaText1.setBackgroundResource(R.drawable.label_textfour_focused);
				}
				guojiaText2.setBackgroundResource(R.drawable.label_textfour_default);
				guojiaText3.setBackgroundResource(R.drawable.label_textfour_default);
				guojiaText4.setBackgroundResource(R.drawable.label_textother_default);
				guojiaText4.setText("选择其他");
				isChooseCountry = true;
				refreshListItem();
			}
		});
		guojiaText2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				guojiaText1.setBackgroundResource(R.drawable.label_textfour_default);
				if(!TextUtils.isEmpty(country) && country.equals("英国")){
					country = "";
					guojiaText2.setBackgroundResource(R.drawable.label_textfour_default);
				}else{
					country = "英国";
					guojiaText2.setBackgroundResource(R.drawable.label_textfour_focused);
				}
				guojiaText3.setBackgroundResource(R.drawable.label_textfour_default);
				guojiaText4.setBackgroundResource(R.drawable.label_textother_default);
				guojiaText4.setText("选择其他");
				isChooseCountry = true;
				refreshListItem();
			}
		});
		guojiaText3.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				guojiaText1.setBackgroundResource(R.drawable.label_textfour_default);
				guojiaText2.setBackgroundResource(R.drawable.label_textfour_default);
				if(!TextUtils.isEmpty(country) && country.equals("澳大利亚")){
					country = "";
					guojiaText3.setBackgroundResource(R.drawable.label_textfour_default);
				}else{
					country = "澳大利亚";
					guojiaText3.setBackgroundResource(R.drawable.label_textfour_focused);
				}
				guojiaText4.setBackgroundResource(R.drawable.label_textother_default);
				guojiaText4.setText("选择其他");
				isChooseCountry = true;
				refreshListItem();
			}
		});
		guojiaText4.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(ZhidaoSearchActivity.this)
				.setTitle("选择其他")
				.setItems(R.array.zhidao_search_country_array, new OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						guojiaText1.setBackgroundResource(R.drawable.label_textfour_default);
						guojiaText2.setBackgroundResource(R.drawable.label_textfour_default);
						guojiaText3.setBackgroundResource(R.drawable.label_textfour_default);
						String selItemName = getApplicationContext().getResources().getStringArray(R.array.zhidao_search_country_array)[arg1];
						country = selItemName;
						guojiaText4.setBackgroundResource(R.drawable.label_textother_focused);
						guojiaText4.setText(selItemName);
						isChooseCountry = true;
						refreshListItem();
					}
				}).show();
			}
		});
		biaoqianText1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(!TextUtils.isEmpty(tag) && tag.equals("山楂申请")){
					tag = "";
					biaoqianText1.setBackgroundResource(R.drawable.label_textfour_default);
				}else{
					tag = "山楂申请";
					biaoqianText1.setBackgroundResource(R.drawable.label_textfour_focused);
				}
				biaoqianText2.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText3.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText4.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText5.setBackgroundResource(R.drawable.label_textfour_default);
				isChooseCountry = true;
				refreshListItem();
			}
		});
		biaoqianText2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				biaoqianText1.setBackgroundResource(R.drawable.label_textfour_default);
				if(!TextUtils.isEmpty(tag) && tag.equals("国外生活")){
					tag = "";
					biaoqianText2.setBackgroundResource(R.drawable.label_textfour_default);
				}else{
					tag = "国外生活";
					biaoqianText2.setBackgroundResource(R.drawable.label_textfour_focused);
				}
				biaoqianText3.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText4.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText5.setBackgroundResource(R.drawable.label_textfour_default);
				isChooseCountry = true;
				refreshListItem();
			}
		});
		biaoqianText3.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				biaoqianText1.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText2.setBackgroundResource(R.drawable.label_textfour_default);
				if(!TextUtils.isEmpty(tag) && tag.equals("办理签证")){
					tag = "";
					biaoqianText3.setBackgroundResource(R.drawable.label_textfour_default);
				}else{
					tag = "办理签证";
					biaoqianText3.setBackgroundResource(R.drawable.label_textfour_focused);
				}
				biaoqianText4.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText5.setBackgroundResource(R.drawable.label_textfour_default);
				isChooseCountry = true;
				refreshListItem();
			}
		});
		biaoqianText4.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				biaoqianText1.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText2.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText3.setBackgroundResource(R.drawable.label_textfour_default);
				if(!TextUtils.isEmpty(tag) && tag.equals("学校交流")){
					tag = "";
					biaoqianText4.setBackgroundResource(R.drawable.label_textfour_default);
				}else{
					tag = "学校交流";
					biaoqianText4.setBackgroundResource(R.drawable.label_textfour_focused);
				}
				biaoqianText5.setBackgroundResource(R.drawable.label_textfour_default);
				isChooseCountry = true;
				refreshListItem();
			}
		});
		biaoqianText5.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				biaoqianText1.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText2.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText3.setBackgroundResource(R.drawable.label_textfour_default);
				biaoqianText4.setBackgroundResource(R.drawable.label_textfour_default);
				if(!TextUtils.isEmpty(tag) && tag.equals("移民政策")){
					tag = "";
					biaoqianText5.setBackgroundResource(R.drawable.label_textfour_default);
				}else{
					tag = "移民政策";
					biaoqianText5.setBackgroundResource(R.drawable.label_textfour_focused);
				}
				isChooseCountry = true;
				refreshListItem();
			}
		});
		searchNameEdit = (EditText)findViewById(R.id.search_name_edit);
		addQuestionText = (TextView)findViewById(R.id.add_new_question_text);
		listView = (ListView)findViewById(R.id.listview);
		adapter = new ListViewAdapter();
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new ListView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bundle bundle = new Bundle();
				bundle.putSerializable("askData", results.get(arg2));
				startActivity(new Intent(getApplicationContext(),ZhidaoAnswerListActivity.class).putExtras(bundle));
			}});
		findViewById(R.id.btn_top_right).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		pullToRefreshListView = (PullToRefreshView)findViewById(R.id.pull_refresh_listview);
		pullToRefreshListView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
			@Override
			public void onHeaderRefresh(PullToRefreshView view) {
				findViewById(R.id.zhidao_no_data_text).setVisibility(View.GONE);
				results.clear();
				adapter.hasMore = true;
				adapter.pageIdx = 1;
				
				RequestParams params = new RequestParams();
				if(searchNameEdit.getText().toString().length()>0){
					params.put("key", searchNameEdit.getText().toString());
				}
				if(!TextUtils.isEmpty(country)){
					params.put("country", country);
				}
				if(!TextUtils.isEmpty(tag)){
					params.put("tag", tag);
				}
				params.put("Page", "1");
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_ZHIDAO_ASK_SEARCH_URL, params, getHandler());
			}
		});
		pullToRefreshListView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
			@Override
			public void onFooterRefresh(PullToRefreshView view) {
				if(!adapter.hasMore){
					pullToRefreshListView.onFooterRefreshComplete();
					return;
				}
				RequestParams params = new RequestParams();
				if(searchNameEdit.getText().toString().length()>0){
					params.put("key", searchNameEdit.getText().toString());
				}
				if(!TextUtils.isEmpty(country)){
					params.put("country", country);
				}
				if(!TextUtils.isEmpty(tag)){
					params.put("tag", tag);
				}
				params.put("Page", ""+adapter.pageIdx);
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_ZHIDAO_ASK_SEARCH_URL, params, getHandler());
			}
		});
		addQuestionText.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(searchNameEdit.getText().toString().length()>0){
					Bundle bundle = new Bundle();
					bundle.putString("searchName", searchNameEdit.getText().toString());
					startActivity(new Intent(getApplicationContext(),ZhidaoAddQuestionActivity.class).putExtras(bundle));
					searchNameEdit.getText().clear();
				}
			}
		});
		searchNameEdit.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				if(arg0.length()>0){
					addQuestionText.setText("+添加新问题");
					if(keyLength!=arg0.length()){
						keyLength = arg0.length();
						refreshListItem();
					}
				}else{
					adapter.notifyDataSetChanged();
					addQuestionText.setText("输入后将为您智能匹配问题");
					refreshListItem();
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
			}
		});
		refreshListItem();
	}
	
	private void refreshListItem(){
		findViewById(R.id.zhidao_no_data_text).setVisibility(View.GONE);
		results.clear();
		adapter.hasMore = true;
		adapter.pageIdx = 1;
		adapter.notifyDataSetChanged();
		
		RequestParams params = new RequestParams();
		if(searchNameEdit.getText().toString().length()>0){
			params.put("key", searchNameEdit.getText().toString());
		}
		if(!TextUtils.isEmpty(country)){
			params.put("country", country);
		}
		if(!TextUtils.isEmpty(tag)){
			params.put("tag", tag);
		}
		params.put("Page", "1");
		params.put("PageSize", ""+Constants.PAGE_SIZE);
		HttpClient.getInstance().get(Constants.API_ZHIDAO_ASK_SEARCH_URL, params, getHandler());
	}

	private class ListViewAdapter extends BaseAdapter{
		public int pageIdx = 1;
		public boolean hasMore = true;
		
		@Override
		public int getCount() {
			return results.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = getLayoutInflater().inflate(R.layout.include_zhi_dao_search_list_item, null);
			}
			ZhidaoAskData askData = results.get(position);
			TextView itemContent = (TextView)convertView.findViewById(R.id.item_answer_content);
			itemContent.setText(askData.getTitle());
			//load more
			if(searchNameEdit.getText().toString().length()>0 && position>=results.size()-1 && hasMore){
				RequestParams params = new RequestParams();
				if(searchNameEdit.getText().toString().length()>0){
					params.put("key", searchNameEdit.getText().toString());
				}
				if(!TextUtils.isEmpty(country)){
					params.put("country", country);
				}
				if(!TextUtils.isEmpty(tag)){
					params.put("tag", tag);
				}
				params.put("Page", ""+pageIdx);
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_ZHIDAO_ASK_SEARCH_URL, params, getHandler());
			}
			return convertView;
		}		
	}
	
}
